package com.zmn.oms.task.job.third.tmall;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.dto.order.proxy.OrderDutyTimeDTO;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.taobao.service.TmallService;
import com.zmn.oms.zmn.business.interfaces.tmall.TmallOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 类描述：给天猫回复预约时间任务
 *
 * @author LiangHailong
 * @date 2019/09/23 20:24
 */
@LTS
@Slf4j
public class ReplyDutyTimeJob {
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;
    @Autowired
    private TmallService tmallService;
    @Autowired
    private TmallOrderBService tmallOrderBService;
    @Autowired
    protected ZsOrderWorkQueryBService zsOrderWorkQueryBService;

    /**
     * 运行回复预约时间任务
     *   如果工单有预约时间，且尚未将预约时间同步给天猫，将预约时间同步给天猫
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_TMALL_REPLY_DUTYTIME_JOB)
    public Result replyDutyTime(Job job){
        String orderIdStr = job.getParam("orderId");
        Long orderId = Long.valueOf(orderIdStr);
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        // 无预约时间的，不执行操作
        if (Objects.isNull(orderWork) || Objects.isNull(orderWork.getDutyTime())) {
            log.info("#Tmall_ReplyDutyTime# orderId:[{}] 无预约时间，不处理！", orderIdStr);
            return new Result(Action.EXECUTE_SUCCESS, "无预约时间，不处理！");
        }

        try {
            // 已同步预约时间的，不执行操作
            List<OrderNotifyLog> orderNotifyLogs = orderNotifyLogBService.listByOrderId(orderId);
            if (!CollectionUtils.isEmpty(orderNotifyLogs)) {
                boolean flag = orderNotifyLogs.stream().anyMatch(log -> {
                    // 找出同步过预约时间，且同步成功的日志
                    boolean isReplyDutyTime = Objects.equals(OrderStatusConsts.ORDER_STATUS_CONFIRM,
                            Integer.parseInt(log.getNotifyStatus()));
                    boolean isSuccess = Objects.equals(StatusConsts.STATUS_SUCCESS, log.getNotifyResultStatus());
                    return (isReplyDutyTime && isSuccess);
                });

                if (flag) {
                    log.info("#Tmall_ReplyDutyTime# orderId:[{}] 已同步过预约时间，不处理！", orderIdStr);
                    return new Result(Action.EXECUTE_SUCCESS, "已同步过预约时间，不处理！");
                }
            }

            // 执行同步操作
            tmallService.syncDutyTime(orderId, job.getTaskId());
            log.info("#comment# 回复预约时间任务执行成功 ！");
            return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
        } catch (Exception e) {
            log.error("预约时间同步失败：orderId={}", orderIdStr);
            return new Result(Action.EXECUTE_FAILED, "预约时间同步失败");
        }

    }

    /**
     * 由于天猫新增订单和修改预约时间消息 同时推送过来
     * 处理天猫推送的预约时间消息需要延迟update
     * 20秒钟后 同步天猫预约时间
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_TMALL_SYNC_DUTYTIME_JOB)
    public Result syncDutyTime(Job job) {
        String outerId = job.getParam("outerId");
        String buyerExpectDate = job.getParam("buyerExpectDate");
        ZsOrderWorkVO orderWork = zsOrderWorkQueryBService.findOrderWorkByOuterId(outerId, null);

        if (orderWork == null) {
            log.info("#Tmall_syncDutyTime# outerId:[{}] 工单不存在，不处理！", outerId);
            return new Result(Action.EXECUTE_SUCCESS, "工单不存在，不处理！");
        }

        // 保存新的预约时间
        try {
            OrderDutyTimeDTO dutyTimeDTO = new OrderDutyTimeDTO();
            dutyTimeDTO.setWorkId(orderWork.getWorkId());
            dutyTimeDTO.setOrderId(orderWork.getOrderId());
            dutyTimeDTO.setChannelId(orderWork.getChannelId());
            dutyTimeDTO.setDutyTime(DateUtil.parse(buyerExpectDate));
            dutyTimeDTO.setChannelId(orderWork.getChannelId());
            dutyTimeDTO.setOuterId(outerId);
            tmallOrderBService.updateOrderWorkDutyTime(dutyTimeDTO);
            return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
        } catch (OmsBaseException e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            log.error(e.getMessage(), e);
            return new Result(Action.EXECUTE_FAILED, "推送给天猫预约时间任务处理失败！");
        }
    }
}
